import tkinter as tk
from tkinter import *
from tkinter.filedialog import *
from tkinter.colorchooser import *
from conf.WindowSettings import *
from func.ConsoleUtil import console, ELogColorType

desc_x = 200
desc_width = 80

class TextEditCore:
    Instance = None
    def __init__(self, root, parent):
        if TextEditCore.Instance != None:
            return
        
        self.root = root
        self.parent = parent
        TextEditCore.Instance = self
        console.log('文本编辑器实例已初始化!', ELogColorType.Cyan)
        # 快捷键配置
        self.shortcut_map = {}
        self.shortcut_map['<Control-n>'] = self.__create_file
        self.shortcut_map['<Control-o>'] = self.__open_file
        self.shortcut_map['<Control-s>'] = self.__save_file
        self.shortcut_map['<Control-q>'] = self.__close

    def show(self):
        if hasattr(self, 'textpad') and self.textpad != None:
            return
        # 构建文本编辑区域渲染
        self.textpad = Text(self.parent)
        self.textpad.place(x=0,y=0)
        tk.Label(self.textpad, text="Ctrl+N 新建").place(x=desc_x, y=180, width=desc_width)
        tk.Label(self.textpad, text="Ctrl+O 打开").place(x=desc_x, y=200, width=desc_width)
        tk.Label(self.textpad, text="Ctrl+S 保存").place(x=desc_x, y=220, width=desc_width)
        tk.Label(self.textpad, text="Ctrl+Q 退出").place(x=desc_x, y=240, width=desc_width)
        for key in self.shortcut_map.keys():
            self.root.bind(key, self.shortcut_map[key])

    def hide(self):
        # 清理文本区域渲染
        self.textpad.destroy()
        self.textpad = None
        for key in self.shortcut_map.keys():
            self.root.unbind(key)

    def __create_file(self, event):
        self.__save_file(event=event)
        self.textpad.delete("1.0", "end")

    def __save_file(self, event):
        self.filename = asksaveasfilename(title='另存为：', initialfile='未命名.txt', filetypes=[("文本文档", "*.txt")], defaultextension=".txt")
        if hasattr(self, "filename") and self.filename != '':
            with open(self.filename, 'w') as f:
                c = self.textpad.get(1.0, END)
                f.write(c)
        else:
            console.error("no file save!")

    def __open_file(self, event):
        self.__save_file(event=event)
        self.textpad.delete("1.0", "end")
        with askopenfile(title="打开文本文件") as f:
            self.textpad.insert(INSERT, f.read())
            self.filename = f.name

    def __close(self, event):
        self.hide()